package com.fwtai.service;

import com.fwtai.quartz.QuartzDeleteOrder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class TaskService{

  private final QuartzDeleteOrder quartzDeleteOrder;

  public TaskService(final QuartzDeleteOrder quartzDeleteOrder){
    this.quartzDeleteOrder = quartzDeleteOrder;
  }

  @Async("taskHanderExecutor")//todo 可以创建多个就可以达到像微信支付通知回调的那个,1,5,10,30,60...之类的通知,此处是移除一个任务（仅在手动删除的成功后才能删除定时任务,也就是 rows > 0 才能调用本方法）
  public void delOrderInfo(final Class<? extends Job> jobClass,final String groupName,final String dateKey,final Long value){
    final String jobName = String.valueOf(value);
    final JobDetail jobDetail = JobBuilder.newJob(jobClass).usingJobData(dateKey,value).withIdentity(jobName,groupName).build();
    final long time = 60 * 1000 * 32;//todo 32分钟
    final SimpleTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName,groupName).startAt(new Date(new Date().getTime()+time))//32分钟后执行
      .withSchedule(SimpleScheduleBuilder.simpleSchedule()
        .withIntervalInMinutes(31)//每隔31分钟执行一次
        .withRepeatCount(2)).build();//重复次数(总共执行3次,因为32分钟后执行1次,加上重复执行2次,共3次)
    //创建调度器Scheduler
    final SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    try {
      final Scheduler scheduler = schedulerFactory.getScheduler();
      //执行
      scheduler.scheduleJob(jobDetail,trigger);
      scheduler.start();
    } catch (final SchedulerException ignored){}
  }

  //调用方式 taskService.delOrderTask(kid);
  public void delOrderTask(final Long value){
    delOrderInfo(QuartzDeleteOrder.class,QuartzDeleteOrder.groupDeleteOrder,QuartzDeleteOrder.dateKey,value);
  }

  @Async("taskHanderExecutor")//移除一个任务,仅在支付成功后回调,即 rows > 0 才能调用本方法(所以在附加的参数中得附加一个订单的id来删除任务),用法 taskService.delJobOrder(kid);
  public void delJobOrder(final Long value){
    quartzDeleteOrder.delOrderHandler(value);
  }
}